package com.samnative.pineapple.main;

import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.LinearSmoothScroller;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.reflect.TypeToken;
import com.samnative.pineapple.adapter.CityAllAdapter;
import com.samnative.pineapple.entity.City;
import com.samnative.pineapple.http.HttpRequest;
import com.samnative.pineapple.http.JsonResult;
import com.samnative.pineapple.instance.AppPrefer;
import com.samnative.pineapple.utils.GsonUtils;
import com.samnative.pineapple.utils.SpaceItemDecoration;
import com.samnative.pineapple.utils.ViewHelper;
import com.samnative.pineapple.value.Config;
import com.samnative.pineapple.widget.RightLetterSeekbar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 城市切换
 */
public class ChangeCitytActivity extends BaseActivity implements OnClickListener {
    /**
     * 城市选择列表
     */
    private RecyclerView lv_city_list;
    /**
     * 热门城市
     */
    private RecyclerView gv_hot_city;
    /**
     * 全部城市列表数据
     */
    private List<City> allCitys;
    /**
     * 适配器
     */
    private CityAllAdapter caAlldapter, caHotAdapter;
    /**
     * 显示当前选择的城市
     */
    private TextView tv_current_city;
    /**
     * 城市搜索
     */
    private EditText search_edit;
    /**
     * 自定义View
     */
    private RightLetterSeekbar seekbar_Right;
    /**
     * 标签提示
     */
    private TextView text_view;

    /**
     * 定义滚动控制器
     */
    private LinearSmoothScroller smoothScroller;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_change_city;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        if (allCitys == null) {
            String json = getFromAssets("city.json");
            if (json.length() > 1) {
                allCitys = GsonUtils.fromJsonList(json,
                        new TypeToken<List<City>>() {
                        }.getType());
            }
        }
        caAlldapter = new CityAllAdapter(R.layout.item_city);
        caHotAdapter = new CityAllAdapter(R.layout.item_city);
        findViewById(R.id.tv_back).setOnClickListener(this);
        seekbar_Right = (RightLetterSeekbar) findViewById(R.id.view_right);
        setRightLetter();
        seekbar_Right.setOnclikViewRight(onclikViewRight);
        text_view = (TextView) findViewById(R.id.text_tag);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        lv_city_list = (RecyclerView) findViewById(R.id.lv_city_list);
        lv_city_list.setLayoutManager(linearLayoutManager);
        caAlldapter.addHeaderView(getHead());
        caAlldapter.addData(allCitys);
        lv_city_list.setAdapter(caAlldapter);
        caAlldapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                AppPrefer.getInstance(mContext).put(
                        AppPrefer.currentCity, allCitys.get(position)
                                .getName());
                AppPrefer.getInstance(mContext).put(
                        AppPrefer.currentCityCode,
                        allCitys.get(position).getId() + "");
                ViewHelper.hideKeyboard(mContext, search_edit);
                finish();
            }
        });


        smoothScroller = new LinearSmoothScroller(mContext) {

            // 这里考虑的是垂直列表
            @Override
            protected int getVerticalSnapPreference() {

                // 固定返回顶对齐方式
                return SNAP_TO_START;
            }
        };


        search_edit = (EditText) findViewById(R.id.search_edit);
        // 监听软键盘确定键
        search_edit
                .setOnEditorActionListener(new TextView.OnEditorActionListener() {
                    @Override
                    public boolean onEditorAction(TextView v, int actionId,
                                                  KeyEvent event) {
                        // TODO Auto-generated method stub
                        // 判断是否是“GO”键
                        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                            String keyWord = search_edit.getText().toString();
                            for (int i = 0; i < allCitys.size(); i++) {
                                String name = allCitys.get(i).getName();
                                if (name.length() > 0 && name.contains(keyWord)) {

                                    try {
                                        // 设置滚动目标 position
                                        smoothScroller.setTargetPosition(i + 1);
                                        // 主动触发滚动
                                        lv_city_list.getLayoutManager().startSmoothScroll(smoothScroller);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }

                                }
                            }
                        }
                        return false;
                    }
                });
        search_edit.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                // TODO Auto-generated method stub

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
                String keyWord = search_edit.getText().toString();
                if (keyWord.length() == 0) {
                    return;
                }
                for (int i = 0; i < allCitys.size(); i++) {
                    String name = allCitys.get(i).getName();
                    if ((name.length() >= keyWord.length())
                            && (name.substring(0, keyWord.length())
                            .equals(keyWord))) {
                        try {
                            // 设置滚动目标 position
                            smoothScroller.setTargetPosition(i + 1);
                            // 主动触发滚动
                            lv_city_list.getLayoutManager().startSmoothScroll(smoothScroller);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }
            }
        });
        requestData();
    }


    /**
     * 统计出所有的导航字母
     */
    private void setRightLetter() {
        List<String> text = new ArrayList<String>();
        for (int i = 0; i < allCitys.size(); i++) {
            String letter = allCitys.get(i).getUcfirst();
            boolean is = false;
            for (int j = 0; j < text.size(); j++) {
                if (letter.equals(text.get(j))) {
                    is = true;
                }
            }
            if (!is) {
                text.add(letter);
            }
        }
        seekbar_Right.setData(text);
    }

    /**
     * 实现索引View的监听接口
     */
    private RightLetterSeekbar.OnclikViewRight onclikViewRight = new RightLetterSeekbar.OnclikViewRight() {
        @Override
        public void seteventUP() {
            text_view.setVisibility(View.GONE);
        }

        @Override
        public void seteventDownAndMove(String str) {
            text_view.setText(str);
            text_view.setVisibility(View.VISIBLE);
            for (int i = 0; i < allCitys.size(); i++) {
                if (str.equals(allCitys.get(i).getUcfirst())) {

                    try {
                        // 设置滚动目标 position
                        smoothScroller.setTargetPosition(i + 1);
                        // 主动触发滚动
                        lv_city_list.getLayoutManager().startSmoothScroll(smoothScroller);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    break;
                }

            }
        }
    };

    /**
     * 初始化头部布局
     *
     * @return
     */
    public View getHead() {
        View headView = getLayoutInflater().inflate(R.layout.head_city_change,
                null);
        tv_current_city = (TextView) headView
                .findViewById(R.id.tv_current_city);
        setCurrentCity();

        gv_hot_city = headView.findViewById(R.id.gv_hot_city);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext, 3);
        gv_hot_city.setLayoutManager(gridLayoutManager);
        gv_hot_city.addItemDecoration(new SpaceItemDecoration(10, 3));
        caHotAdapter.setGravity(Gravity.CENTER);
        gv_hot_city.setAdapter(caHotAdapter);

        caHotAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                AppPrefer.getInstance(mContext).put(
                        AppPrefer.currentCity, caHotAdapter.getData().get(position)
                                .getName());
                AppPrefer.getInstance(mContext).put(
                        AppPrefer.currentCityCode, caHotAdapter.getData().get(position).getId() + "");
                ViewHelper.hideKeyboard(mContext, search_edit);
                finish();

            }
        });

        return headView;
    }


    /**
     * 显示当前定位到的城市
     */
    public void setCurrentCity() {
        if (Config.currentCity != null) {
            tv_current_city.setText(Config.currentCity);
            tv_current_city.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    for (int i = 0; i < allCitys.size(); i++) {
                        if (allCitys.get(i).getName().equals(Config.currentCity)) {
                            AppPrefer.getInstance(mContext).put(
                                    AppPrefer.currentCity,
                                    allCitys.get(i).getName());
                            AppPrefer.getInstance(mContext).put(
                                    AppPrefer.currentCityCode, allCitys
                                            .get(i).getId() + "");
                            ViewHelper.hideKeyboard(mContext, search_edit);
                            finish();
                        }
                    }
                }
            });
        } else {
            tv_current_city.setText("定位中...");

            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (isFinishing()) {
                        return;
                    }
                    setCurrentCity();
                }
            }, 3000);
        }
    }

    /**
     * 请求数据
     */
    public void requestData() {

        Map<String, String> map = new HashMap<>();
        map.put("_apiname", "stobusiness.index.getCity");
        map.put("mtoken", AppPrefer.getInstance(mContext).getString(AppPrefer.mtoken, ""));
        HttpRequest.post(this, "", map, new JsonResult() {
            @Override
            public void reqestSuccess(JSONObject result) {
                try {
                    JSONObject jsonData = result
                            .getJSONObject("data");
                    JSONArray jsonArrHot = jsonData.getJSONArray("hot");

                    List<City> list = GsonUtils.fromJsonList(
                            jsonArrHot.toString(),
                            new TypeToken<List<City>>() {
                            }.getType());
                    caHotAdapter.addData(list);
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }


            }

            @Override
            public void requestFailure(int code, String msg) {
                super.requestFailure(code, msg);
            }

            @Override
            public void requestFinish() {
                super.requestFinish();
            }
        });

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.tv_back:
                ViewHelper.hideKeyboard(mContext, search_edit);
                finish();
                break;
            default:
                break;
        }
    }

    /**
     * 读取本地
     *
     * @param fileName
     * @return
     */
    public String getFromAssets(String fileName) {
        try {
            InputStreamReader inputReader = new InputStreamReader(
                    getResources().getAssets().open(fileName));
            BufferedReader bufReader = new BufferedReader(inputReader);
            String line = "";
            String Result = "";
            while ((line = bufReader.readLine()) != null)
                Result += line;
            return Result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }
}
